<template>
    <div class="n1">
        <el-form :model="data" :rules="mRules" ref="form" label-width="auto">
            <el-card>
                <div slot="header" class="clearfix">
                    <span>新增角色</span>
                </div>
                <div>
                    <el-form-item label="角色名" prop="name" :show-message="true">
                        <el-input v-model="data.name" placeholder="暂无数据"/>
                    </el-form-item>
                    <el-form-item label="键" prop="code">
                        <el-input v-model="data.code" placeholder="暂无数据"/>
                    </el-form-item>
                </div>
            </el-card>
            <el-card>
                <div slot="header" class="clearfix">
                    <span>角色菜单</span>
                </div>
                <div>
                    <el-form-item>
                        <el-col :span="24">
                            <el-input v-model="filterMenuText"
                                      style="width: 40%;margin-right: 5px"
                                      @keyup.native="filterTextMenuChange()"
                                      placeholder="输入标签内容进行查询"/>
                            <el-tooltip content="展开" placement="top-start">
                                <el-button @click="menuOpenAll" size="mini" type="info" plain
                                           icon="el-icon-arrow-down"/>
                            </el-tooltip>
                            <el-tooltip content="折叠" placement="top-start">
                                <el-button @click="menuCloseAll" type="info" plain size="mini" icon="el-icon-arrow-up"/>
                            </el-tooltip>
                            <el-tooltip content="全选" placement="top-start">
                                <el-button @click="menuCheckAll" size="mini" type="info" plain
                                           icon="el-icon-check"/>
                            </el-tooltip>
                            <el-tooltip content="反选" placement="top-start">
                                <el-button @click="menuClearCheck" type="info" plain
                                           size="mini" icon="el-icon-close"/>
                            </el-tooltip>
                        </el-col>
                    </el-form-item>
                    <el-form-item>
                        <el-tree
                                ref="menus"
                                node-key="id"
                                :data="treeMenus"
                                :check-strictly="false"
                                :default-checked-keys="menuCheckIds"
                                :default-expanded-keys="menuCheckIds"
                                :filter-node-method="filterNodeMenu"
                                show-checkbox>
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <el-tag size="small">{{data.title}}</el-tag>
                        <el-tag size="small" class="let2">{{data.path}}</el-tag>
                    </span>
                        </el-tree>
                    </el-form-item>
                </div>
            </el-card>
            <el-card>
                <div slot="header" class="clearfix">
                    <span>角色权限</span>
                </div>
                <div>
                    <el-form-item>
                        <el-col line :span="24">
                            <el-input v-model="filterResourceText"
                                      @keyup.native="filterResourceChange()"
                                      style="width: 40%;margin-right: 5px"
                                      placeholder="输入标签内容进行查询"/>
                            <el-tooltip content="展开" placement="top-start">
                                <el-button @click="resourceOpenAll" size="mini" type="info" plain
                                           icon="el-icon-arrow-down"/>
                            </el-tooltip>
                            <el-tooltip content="折叠" placement="top-start">
                                <el-button @click="resourceCloseAll" type="info" plain size="mini"
                                           icon="el-icon-arrow-up"/>
                            </el-tooltip>
                            <el-tooltip content="全选" placement="top-start">
                                <el-button @click="resourceCheckAll" size="mini" type="info" plain
                                           icon="el-icon-check"/>
                            </el-tooltip>
                            <el-tooltip content="反选" placement="top-start">
                                <el-button @click="clearResourceCheck" type="info"
                                           plain size="mini" icon="el-icon-close"/>
                            </el-tooltip>
                        </el-col>

                    </el-form-item>
                    <el-form-item>
                        <el-tree
                                ref="resources"
                                node-key="id"
                                :data="treeResources"
                                :check-strictly="false"
                                :default-checked-keys="resourceCheckIds"
                                :default-expanded-keys="resourceCheckIds"
                                :filter-node-method="filterNodeResource"
                                show-checkbox
                        >
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <el-tag size="small">{{data.name}}</el-tag>
                        <el-tag size="small" class="let2">{{data.url}}</el-tag>
                     </span>
                        </el-tree>
                    </el-form-item>
                </div>
            </el-card>
        </el-form>

        <div class="toolbar-bottom-right">
            <el-button class="button" size="medium" @click="close()">取消</el-button>
            <el-button v-if="option.type==='insert'" class="button" type="primary" size="medium" @click="insert()">添加
            </el-button>
            <el-button v-if="option.type==='update'" class="button" type="primary" size="medium" @click="update()">修改
            </el-button>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Emit, Prop} from 'vue-property-decorator'
    import {API} from "@/core/api/API";
    import {ElForm} from "element-ui/types/form";
    import {mixins} from "vue-class-component";
    import BaseVue from "@/core/mixin/BaseVue";
    import {errorMsg, successMsg} from "@/core/utils/message";
    import $http from "@/core/utils/http";
    import {rule} from "@/core/utils/rule";
    import Kit from "@/core/mixin/Kit";
    import {copy, isBlank, tree} from "@/core/utils/Utils";

    @Component({
        name: 'RoleEdit',
        components: {},
    })
    export default class RoleEdit extends mixins(BaseVue, Kit) {
        @Prop({default: {}}) data!: any;
        @Prop({default: {type: 'insert', title: '添加'}}) option!: any;
        menus = [];
        menuCheckIds = [];

        resources = [];
        resourceCheckIds = [];

        //关闭时是否刷新分页
        backRefresh: boolean = false;

        mRules = {
            name: [rule.notNullBlur()],
            code: [rule.notNullBlur()],
        };

        get treeResources() {
            return tree(this.resources);
        }

        get treeMenus() {
            return tree(this.menus);
        }

        //初始化
        async mounted() {
            this.data = copy(this.data);
            this.roleMenu();
            this.roleResource();
        }

        //重新获取焦点
        activated() {
        }

        //失去焦点
        deactivated() {
        }

        //添加用户
        insert() {
            (this.$refs.form as ElForm).validate().then(() => {
                $http.post(API.sysRoleInsert, this.data).then((res: any) => {
                    if (res.success) {
                        this.backRefresh = true;
                        successMsg("已添加");
                    }
                });
            },).catch(() => {
                errorMsg("表单内容填写错误，请检查！");
            });
        }

        roleMenu() {
            $http.post(API.sysRoleMenu, {id: this.data.id}).then((res: any) => {
                if (res.success) {
                    this.menus = res.menus;
                    this.menuCheckIds = res.menuCheckIds;
                }
            });
        }

        roleResource() {
            $http.post(API.sysRoleResource, {id: this.data.id}).then((res: any) => {
                if (res.success) {
                    this.resources = res.resources;
                    this.resourceCheckIds = res.resourceCheckIds;
                }
            });
        }

        //修改用户
        update() {
            (this.$refs.form as ElForm).validate().then(() => {
                this.data.menuCheckIds = (this.$refs.menus as any).getCheckedKeys();
                this.data.resourceCheckIds = (this.$refs.resources as any).getCheckedKeys();
                $http.post(API.sysRoleUpdate, this.data).then((res: any) => {
                    if (res.success) {
                        this.backRefresh = true;
                        successMsg("操作成功");
                    }
                });
            }).catch(() => {
                errorMsg("表单内容填写错误，请检查！");
            });
        }

        //关闭事件
        @Emit("close")
        close() {
            return {refresh: this.backRefresh};
        }


        /**
         * 处理树
         */
        filterMenuText = "";
        filterResourceText = "";

        //菜单展开
        menuOpenAll() {
            for (let i = 0; i < (this.$refs.menus as any).store._getAllNodes().length; i++) {
                (this.$refs.menus as any).store._getAllNodes()[i].expanded = true;
            }
        }

        //菜单折叠
        menuCloseAll() {
            for (let i = 0; i < (this.$refs.menus as any).store._getAllNodes().length; i++) {
                (this.$refs.menus as any).store._getAllNodes()[i].expanded = false;
            }
        }

        //菜单全选
        menuCheckAll() {
            (this.$refs.menus as any).setCheckedNodes(tree(this.menus))
        }

        //菜单反选
        menuClearCheck() {
            (this.$refs.menus as any).setCheckedKeys([])
        }

        //资源展开
        resourceOpenAll() {
            for (let i = 0; i < (this.$refs.resources as any).store._getAllNodes().length; i++) {
                (this.$refs.resources as any).store._getAllNodes()[i].expanded = true;
            }
        }

        //资源折叠
        resourceCloseAll() {
            for (let i = 0; i < (this.$refs.resources as any).store._getAllNodes().length; i++) {
                (this.$refs.resources as any).store._getAllNodes()[i].expanded = false;
            }
        }

        //资源全选
        resourceCheckAll() {
            (this.$refs.resources as any).setCheckedNodes(tree(this.resources))
        }

        //资源反选
        clearResourceCheck() {
            (this.$refs.resources as any).setCheckedKeys([])
        }

        //文字筛选菜单
        filterTextMenuChange() {
            (this.$refs.menus as any).filter(this.filterMenuText)
        }

        //文字筛选资源
        filterResourceChange() {
            (this.$refs.resources as any).filter(this.filterResourceText)
        }

        filterNodeMenu(value: any, data: any) {
            if (isBlank(value)) return true;
            let path = false;
            let redirect = false;
            let title = false;
            if (data.path) {
                path = data.path.indexOf(value) != -1
            }
            if (data.redirect) {
                redirect = data.redirect.indexOf(value) != -1
            }
            if (data.title) {
                title = data.title.indexOf(value) != -1
            }
            return path || redirect || title;
        }

        filterNodeResource(value: any, data: any) {
            if (isBlank(value)) return true;
            let ability = false;
            let name = false;
            let url = false;
            if (data.ability) {
                ability = data.ability.indexOf(value) != -1
            }
            if (data.name) {
                name = data.name.indexOf(value) != -1
            }
            if (data.url) {
                url = data.url.indexOf(value) != -1
            }
            return ability || name || url;
        }


    }


</script>

<style scoped lang="scss">

</style>
